package com.github.livebase.storage;

import com.github.livebase.database.LiveDatabaseHelper;
import com.github.livebase.database.StorageOperator;
import com.github.livebase.plugins.PluginContext;
import com.google.gson.Gson;

import java.nio.charset.StandardCharsets;

/**
 * @ClassName Proxy
 * @description:
 * @author: biao532
 * @create: 2024-02-06 14:15
 * @Version 1.0
 **/
public class PluginsStorage extends LStorage {

    private static class GsonConverter implements Converter {
        private static Gson gson = new Gson();
        private ClassLoader classLoader;
        public GsonConverter(ClassLoader classLoader) {
            this.classLoader = classLoader;
        }

        @Override
        public <T> byte[] toString(T value) {
            return gson.toJson(value).getBytes(StandardCharsets.UTF_8);
        }

        @Override
        public <T> T fromString(StorageOperator.StorageEntity entity) throws Exception {
            Class clazz = classLoader.loadClass(entity.getClazz());
            return (T) gson.fromJson(new String(entity.getValue()), clazz);
        }
    }

    public PluginsStorage(PluginContext context, LiveDatabaseHelper op) {
        super(context.getName(), context.getPluginVersion(), new GsonConverter(context.getClassLoader()), op.getStorageOperator());
    }
}
